
import time, os, sys
import cPickle, pickle

from dexen.system.libs import _constants
from dexen.system.libs._dexen_api import ManagerAPI
from dexen.libs import dexen_api

PICKLE_PROTOCOL = pickle.HIGHEST_PROTOCOL

def script_executor(schema_name, pop_name, script_name,
                    file_name, function_name, url, times, state):

    dexen_api._createScriptApi(url, schema_name, pop_name, script_name)
    sys.path.append(os.path.join(_constants._TEMP_SCHEMA_DIR, schema_name))    

    prev_path = os.getcwd()
    os.chdir(os.path.join(_constants._TEMP_SCHEMA_DIR, schema_name))
    module = __import__(file_name, fromlist=[""])
    func = getattr(module, function_name)
    
    manager_api = ManagerAPI(url, schema_name, pop_name) 
    
    if times == -1:
        while state.value == _constants._ALIVE:
            func()
            if manager_api.hasPopulationStopped():
                break                                     
    else:
        while times > 0 and state.value == _constants._ALIVE:
            func()
            times -= 1
            if manager_api.hasPopulationStopped():
                break

    state.value = _constants._DEAD
    return